/**
 * 
 */
package me.myachievements.web;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author besseym
 *
 */
public abstract class MyAchievementsServlet extends HttpServlet {
	
	protected static final String PLAIN_CONTENT_TYPE = "text/plain; charset=UTF-8";
	protected static final String HTML_CONTENT_TYPE = "text/html; charset=UTF-8";
	protected static final String XML_CONTENT_TYPE = "text/xml; charset=UTF-8";
	
	private static final String ERROR_VIEW = "/WEB-INF/view/error.jsp";
	
	/**
	 * Perform Servlet Action.
	 * @throws Exception
	 */
	public abstract void performAction(HttpServletRequest request, HttpServletResponse response) throws Exception;

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init()
	 */
	@Override
	public void init() throws ServletException {
		
	}
	
	public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		try{
			performAction(request, response);
		}
		catch(Exception exception){
			exception.printStackTrace();
    		gotoPage(ERROR_VIEW, request, response);
		}
	}
	
	/**
	 * 
	 * @param uri
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	protected void gotoPage(String uri, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		response.setContentType(HTML_CONTENT_TYPE);
		RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher(uri);
		dispatcher.forward(request, response);
	}
	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
